<?php

namespace App\Model;

use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\Component\Pool\PoolManager;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\Spl\SplBean;

class BaseModel{
    protected $db;
    protected $table;
    protected $perPage = 10;

    public function __construct(){
        $db = PoolManager::getInstance()
            ->getPool(MysqlPool::class)
            ->getObj(Config::getInstance()->getConf('MYSQL.POOL_TIME_OUT'));
        // 请注意判断类型 避免拿到非期望的对象产生误操作
        if($db instanceof MysqlObject) {
            Logger::getInstance()->log('连接池进来了','database');
            $this->db = $db;
        }else{
            throw new \Exception('mysql pool is empty');
        }
    }

    public function __destruct(){
        // 请注意判断类型 避免将不属于该链接池的对象回收到池中
        if($this->db instanceof MysqlObject) {
            Logger::getInstance()->log('连接池进来了','database');
            PoolManager::getInstance()->getPool(MysqlPool::class)->recycleObj($this->db);
        }
    }

    /**
     * 新增
     * @param $bean
     * @return mixed
     */
    public function create($bean) {
        return $this->db->insert($this->table,$bean->toArray(null, SplBean::FILTER_NOT_NULL));//1代表null值的过滤，详情请参考EasySwoole\Spl\SplBean  FILTER_NOT_NULL
    }

    /**
     * 更新
     * @param $bean
     * @param array $data
     * @return bool
     */
    public function update($bean, $data):bool {
        $result = $this->db->where('id', $bean->getId())->update($this->table, $data);
        return $result;
    }

    /**
     * 删除
     * @param $bean
     * @param array $data
     * @return bool
     */
    public function destroy($bean){
        return $this->db->where('id', $bean->getId())->delete($this->table, 1);
    }

    /**
     * 分页大小
     * @return int
     */
    protected function getPerPage(){
        return $this->perPage;
    }
}
